package com.gitee.wsl.android.ui.ext

import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow


object PopupWindowExt {
    fun showPopupWindow(anchorView: View, contentView: View) {
        val popupWindow = PopupWindow(
            contentView,
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
        )

        // 计算 PopupWindow 在屏幕中的位置
        val location = IntArray(2)
        anchorView.getLocationOnScreen(location)
        val anchorX = location[0]
        val anchorY = location[1]
        val anchorWidth = anchorView.width
        val anchorHeight = anchorView.height
        val screenWidth: Int = anchorView.context.resources.displayMetrics.widthPixels
        val screenHeight: Int = anchorView.context.resources.displayMetrics.heightPixels

        // 判断 PopupWindow 是否超出屏幕范围
        val isOverX = anchorX + popupWindow.width > screenWidth
        val isOverY = anchorY + anchorHeight + popupWindow.height > screenHeight

        // 如果超出了屏幕范围，调整 PopupWindow 的位置
        if (isOverX) {
            popupWindow.width = screenWidth - anchorX
        }
        if (isOverY) {
            popupWindow.height = screenHeight - anchorY - anchorHeight
        }

        // 显示 PopupWindow
        popupWindow.showAtLocation(anchorView, Gravity.NO_GRAVITY, anchorX, anchorY + anchorHeight)
    }

}